import json
from typing import List, Dict, Any
from .car_extras import CarExtras


class CarObject:
    """
    车款实体类
    用于表示具体的车辆型号配置
    唯一性确认：modelName + drive 是唯一值
    
    Version 2.0: 添加对多种驱动方式的支持
    """
    
    def __init__(self, series_name: str, model_name: str, price: str, drive: str = ""):
        """
        初始化车款对象
        
        Args:
            series_name (str): 车系名称，外键，用来与车系对应
            model_name (str): model名称
            price (str): 价格字符串
            drive (str): drive字符串 (为保持向后兼容性保留，建议使用drive_types)
        """
        self.series_name = series_name
        self.model_name = model_name
        self.price = price
        self.drive = drive  # 保持向后兼容性
        
        # 新增：支持多种驱动方式
        self.drive_types: List[Dict[str, str]] = []
        
        # 新增：支持多种车身样式（与驱动方式关联）
        self.body_styles: List[Dict[str, str]] = []
        
        # 如果提供了drive参数，自动添加到drive_types中
        if drive:
            self.add_drive_type(drive, "Standard")
        
        self.key_features: List[str] = []
        self.specifications: Dict[str, str] = {}
        self.body_style: str = ""
        self.colors: List[str] = []
        self.interiors: List[str] = []
        self.extras_list: List[CarExtras] = []
    
    def add_drive_type(self, drive_name: str, price: str = "Standard", description: str = ""):
        """
        添加驱动方式选项
        
        Args:
            drive_name (str): 驱动方式名称 (如 "Front Wheel Drive", "All Wheel Drive")
            price (str): 价格信息 (如 "Standard", "+£2,000")
            description (str): 描述信息
        """
        if drive_name:
            # 检查是否已存在
            for existing_drive in self.drive_types:
                if existing_drive.get('name') == drive_name:
                    # 更新现有记录
                    existing_drive.update({
                        'price': price,
                        'description': description
                    })
                    return
            
            # 添加新记录
            drive_data = {
                'name': drive_name,
                'price': price,
                'description': description
            }
            self.drive_types.append(drive_data)
            
            # 如果这是第一个驱动方式，同时更新传统的drive字段
            if not self.drive:
                self.drive = drive_name
    
    def get_drive_types_count(self) -> int:
        """
        获取驱动方式数量
        
        Returns:
            int: 驱动方式的数量
        """
        return len(self.drive_types)
    
    def get_primary_drive_type(self) -> str:
        """
        获取主要驱动方式（第一个驱动方式或传统drive字段）
        
        Returns:
            str: 主要驱动方式名称
        """
        if self.drive_types:
            return self.drive_types[0].get('name', '')
        return self.drive
    
    def has_drive_type(self, drive_name: str) -> bool:
        """
        检查是否包含指定的驱动方式
        
        Args:
            drive_name (str): 驱动方式名称
            
        Returns:
            bool: 是否包含该驱动方式
        """
        for drive_type in self.drive_types:
            if drive_type.get('name', '').lower() == drive_name.lower():
                return True
        return False
    
    def add_bodystyle(self, bodystyle_name: str, associated_drive: str = "", price: str = "Standard", description: str = ""):
        """
        添加车身样式选项
        
        Args:
            bodystyle_name (str): 车身样式名称 (如 "5-door Hatchback", "Estate")
            associated_drive (str): 关联的驱动方式
            price (str): 价格信息 (如 "Standard", "+£1,200")
            description (str): 描述信息
        """
        if bodystyle_name:
            # 检查是否已存在相同的组合
            for existing_bodystyle in self.body_styles:
                if (existing_bodystyle.get('name') == bodystyle_name and 
                    existing_bodystyle.get('associated_drive') == associated_drive):
                    # 更新现有记录
                    existing_bodystyle.update({
                        'price': price,
                        'description': description
                    })
                    return
            
            # 添加新记录
            bodystyle_data = {
                'name': bodystyle_name,
                'associated_drive': associated_drive,
                'price': price,
                'description': description
            }
            self.body_styles.append(bodystyle_data)
    
    def get_body_styles_count(self) -> int:
        """
        获取车身样式数量
        
        Returns:
            int: 车身样式的数量
        """
        return len(self.body_styles)
    
    def get_bodystyles_for_drive(self, drive_name: str) -> List[Dict[str, str]]:
        """
        获取指定驱动方式下的所有车身样式
        
        Args:
            drive_name (str): 驱动方式名称
            
        Returns:
            List[Dict[str, str]]: 该驱动方式下的车身样式列表
        """
        result = []
        for bodystyle in self.body_styles:
            if bodystyle.get('associated_drive', '').lower() == drive_name.lower():
                result.append(bodystyle)
        return result
    
    def has_bodystyle(self, bodystyle_name: str, drive_name: str = "") -> bool:
        """
        检查是否包含指定的车身样式
        
        Args:
            bodystyle_name (str): 车身样式名称
            drive_name (str): 驱动方式名称（可选）
            
        Returns:
            bool: 是否包含该车身样式
        """
        for bodystyle in self.body_styles:
            name_match = bodystyle.get('name', '').lower() == bodystyle_name.lower()
            drive_match = not drive_name or bodystyle.get('associated_drive', '').lower() == drive_name.lower()
            
            if name_match and drive_match:
                return True
        return False
    
    def getKeyFeaturesCount(self) -> int:
        """
        输出当前的keyFeatures个数
        
        Returns:
            int: keyFeatures的数量
        """
        return len(self.key_features)
    
    def getColorsCount(self) -> int:
        """
        输出当前colors的数量
        
        Returns:
            int: colors的数量
        """
        return len(self.colors)
    
    def getSpecificationsCount(self) -> int:
        """
        输出当前的specifications的数量
        
        Returns:
            int: specifications的数量
        """
        return len(self.specifications)
    
    def add_key_feature(self, feature: str):
        """添加关键特性"""
        if feature and feature not in self.key_features:
            self.key_features.append(feature)
    
    def add_specification(self, key: str, value: str):
        """添加规格参数"""
        self.specifications[key] = value
    
    def add_color(self, color: str):
        """添加颜色"""
        if color and color not in self.colors:
            self.colors.append(color)
    
    def add_interior(self, interior: str):
        """添加内饰"""
        if interior and interior not in self.interiors:
            self.interiors.append(interior)
    
    def add_extra(self, extra: CarExtras):
        """添加选装件"""
        if extra and extra not in self.extras_list:
            self.extras_list.append(extra)
    
    def get_unique_id(self) -> str:
        """
        获取唯一标识符
        
        Returns:
            str: modelName + drive 的组合
        """
        return f"{self.model_name}_{self.drive}"
    
    def toJSONString(self) -> str:
        """
        输出符合output.json格式的JSON字符串
        
        Returns:
            str: JSON格式的字符串
        """
        data = {
            "model_name": self.model_name,
            "price": self.price,
            "drive": self.drive,  # 保持向后兼容性
            "drive_types": self.drive_types,  # 新增：多种驱动方式支持
            "body_styles": self.body_styles,  # 新增：车身样式支持
            "key_features": self.key_features,
            "specifications": self.specifications,
            "body_style": self.body_style,  # 保持向后兼容性
            "colors": self.colors,
            "interiors": self.interiors,
            "extras": [extra.to_dict() for extra in self.extras_list]
        }
        return json.dumps(data, ensure_ascii=False, indent=4)
    
    def to_dict(self) -> Dict[str, Any]:
        """
        转换为字典格式
        
        Returns:
            Dict[str, Any]: 字典格式的数据
        """
        return {
            "model_name": self.model_name,
            "price": self.price,
            "drive": self.drive,  # 保持向后兼容性
            "drive_types": self.drive_types,  # 新增：多种驱动方式支持
            "body_styles": self.body_styles,  # 新增：车身样式支持
            "key_features": self.key_features,
            "specifications": self.specifications,
            "body_style": self.body_style,  # 保持向后兼容性
            "colors": self.colors,
            "interiors": self.interiors,
            "extras": [extra.to_dict() for extra in self.extras_list]
        }
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"CarObject(model={self.model_name}, drive={self.drive}, price={self.price})"
    
    def __repr__(self) -> str:
        """详细字符串表示"""
        return (f"CarObject(series_name='{self.series_name}', model_name='{self.model_name}', "
                f"price='{self.price}', drive='{self.drive}')")
    
    def __eq__(self, other) -> bool:
        """相等性比较"""
        if not isinstance(other, CarObject):
            return False
        return self.get_unique_id() == other.get_unique_id()
    
    def __hash__(self) -> int:
        """哈希值"""
        return hash(self.get_unique_id())
